package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.apis.wemedia.IWemediaClient;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.HotArticleService;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Transactional
@Service
public class HotArticleServiceImpl implements HotArticleService {
    @Autowired
    private ApArticleMapper apArticleMapper;
    @Autowired
    private CacheService cacheService;
    @Autowired
    private IWemediaClient wemediaClient;

    /**
     * 计算热点文章
     */
    @Override
    public void computeHotArticle() {
        //过去15天的时间,因为我们添加的数据比较少,5天看不出效果
        Date date = DateTime.now().minusDays(15).toDate();
        List<ApArticle> articleListByDays = apArticleMapper.findArticleListByDays(date);
      //计算文章分值
        List<HotArticleVo> HotArticleVoList =computeHotArticle(articleListByDays);
        //给每个频道缓存30条分值较高的文章
        cacheTagToRedis(HotArticleVoList);

    }

    /**
     * 添加数据到redis中
     * @param hotArticleVoList
     */
    private void cacheTagToRedis(List<HotArticleVo> hotArticleVoList) {
        ResponseResult responseResult = wemediaClient.getChannels();
        if (responseResult.getCode()==200){
            Object data = responseResult.getData();
            String jsonString = JSON.toJSONString(data);
            List<WmChannel> wmChannels = JSON.parseArray(jsonString, WmChannel.class);
            for (WmChannel wmChannel : wmChannels) {
                List<HotArticleVo> collect = hotArticleVoList.stream().filter(item -> item.getChannelId()==wmChannel.getId()).collect(Collectors.toList());
                List<HotArticleVo> dataHotArticleVo = collect.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed()).limit(30).collect(Collectors.toList());
                cacheService.set(ArticleConstants.HOT_ARTICLE_FIRST_PAGE+wmChannel.getId(),JSON.toJSONString(dataHotArticleVo));
            }
        }
        //给推荐频道设置缓存
        hotArticleVoList = hotArticleVoList.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed())
                .limit(30)
                .collect(Collectors.toList());
        cacheService.set(ArticleConstants.HOT_ARTICLE_FIRST_PAGE+ArticleConstants.DEFAULT_TAG,JSON.toJSONString(hotArticleVoList));
    }

    /**
     * 计算过去时间的每个文章的得分
     * @param articleListByDays
     * @return
     */
    private List<HotArticleVo> computeHotArticle(List<ApArticle> articleListByDays) {
        ArrayList<HotArticleVo> hotArticleVos = new ArrayList<>();
        if (null!=articleListByDays&&articleListByDays.size()>0){
            for (ApArticle article : articleListByDays) {
                HotArticleVo hotArticleVo = new HotArticleVo();
                BeanUtils.copyProperties(article,hotArticleVo);
                Integer score = computeScore(article);
                hotArticleVo.setScore(score);
                hotArticleVos.add(hotArticleVo);
            }return hotArticleVos;
        }else {
            return new ArrayList<>();
        }
    }

    /**
     * 计算分支
     * @param article
     * @return
     */
    private Integer computeScore(ApArticle article) {
        int score=0;
        if (null!=article.getLikes()){
         score+=article.getLikes()* ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }
        if (null!=article.getViews()){
            score+=article.getViews();
        }
        if (null!=article.getComment()){
            score+=article.getComment()* ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }
        if (null!=article.getCollection()){
            score+=article.getCollection()* ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }
        return score;
    }
}
